﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BEPUphysics.Entities;
using BEPUphysics.Collidables;
using Microsoft.Xna.Framework;
using BEPUphysics.Collidables.MobileCollidables;

namespace MagicArenaFramework.GameObject.Components.ConcreteTypes
{
    public class EntityFollow : GoComponent
    {
        public delegate void CollisionDel(Collidable other);

        public Entity Self{get;private set;}
        public Entity Follow { get; private set; }
        float Speed;
        Vector3 Vel;
        CollisionDel OnCollideOther;
        CollisionDel OnColliderTarget;

        public EntityFollow(Entity self, Entity follow, CollisionDel onCollideOther, CollisionDel onColliderTarget, float speed = 10)
        {
            Self = self;
            Follow = follow;
            OnCollideOther = onCollideOther;
            OnColliderTarget = onColliderTarget;
            Speed = speed;
            // Add custom method to collider
            Self.CollisionInformation.Events.ContactCreated += new BEPUphysics.Collidables.Events.ContactCreatedEventHandler<BEPUphysics.Collidables.MobileCollidables.EntityCollidable>(Events_ContactCreated);
            Self.CollisionInformation.CollisionRules.Specific.Add(Follow.CollisionInformation.CollisionRules, BEPUphysics.CollisionRuleManagement.CollisionRule.NoSolver);
            Self.CollisionInformation.CollisionRules.Personal = BEPUphysics.CollisionRuleManagement.CollisionRule.NoBroadPhase;
            // Add del
            this.UpdateDel = MyUpdate;
        }

        void MyUpdate(float dt)
        {
            Vector3 traj = Follow.Position - Self.Position;
            traj.Normalize();
            Vel = traj*Speed;
            Self.Position += Vel * dt;
        }

        void Events_ContactCreated(BEPUphysics.Collidables.MobileCollidables.EntityCollidable sender, Collidable other, BEPUphysics.NarrowPhaseSystems.Pairs.CollidablePairHandler pair, BEPUphysics.CollisionTests.ContactData contact)
        {
            if (other is EntityCollidable)
            {
                Entity ent = (other as EntityCollidable).Entity;
                if (Follow.Equals(ent)) OnColliderTarget(other);
                else OnCollideOther(other);
            }
            else OnCollideOther(other);
        }
    }
}
